var Modal = require("./modal.js")

class Handle{
  static cancle=false
  static configure(mesh, deviceKey, address, deviceId, callback, times, message) {
    if (Handle.cancle) {
      if (message != null) Modal.showErr(message);
      return;
    } 
    if (times == null) times = 5;
    if (times <= 0) {
      mesh.init();
      Modal.showErr(message);
      return;
    }
    console.log("configure times:", times);
    Modal.load('配置中');
    mesh.configure(deviceKey, address, function (res) {
      Modal.load('配置结束');
      Modal.loadfinish();
      if (res.code == 0) {
        if (callback) callback({ code: 0, uuid: deviceId, devicekey: deviceKey });
      } else {
        Handle.configure(mesh, deviceKey, address, deviceId, callback, --times, res.message);
      }
    })
  }
  static findProxy(mesh, deviceId, callback, times,res) {
    if (mesh.status ) return;
    if (times == null) times = 5;
    if (times <= 0) {
      callback(res);
      return;
    }
    console.log("findProxy times:", times);
    mesh.findProxy(deviceId, function (res) {
      if (res.code == 0) {
        callback(res);
      } else {
        Handle.findProxy(mesh, deviceId, callback, --times, res);
      }
    })
  }
  static add(mesh, deviceId, address, callback, times, message) {
    if (Handle.cancle){
      if (message != null) Modal.showErr(message);
      return;
    } 
    if(times==null) times=5;
    if (times <= 0) {
      Modal.showErr(message);
      mesh.status=null;
      return;
    }
    Modal.load("添加设备");
    console.log("addDevice times:", times);
    mesh.status = "addDevice";
    mesh.addDevice(deviceId, address, function (res) {
      if (res.code == 0) {
        if (!res.data) Modal.load(res.message);
        else {
          mesh.status = null;
          Handle.findProxy(mesh, deviceId, (result)=>{
            if(result.code!=0) {
              Modal.showErr(message);
              return;
            }
            Handle.configure(mesh, res.data.deviceKey, address, deviceId, callback);
          });
        }
      } else {
        Handle.add(mesh, deviceId, address, callback, --times, res.message);
      }
    });
  }
  static cancle_add(){
    Handle.cancle=true;
    Modal.hideLoading();
  }
}
module.exports = Handle;
